package twitterInfoEngine;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import util.FileUtil;

import dao.TweetsDAO;
import daoImp.ConnectionPool;
import daoImp.TweetsDAOImp;

public class TweetsCollector extends Thread{
	//private static TweetsCollector uniqueInstance = new TweetsCollector();
	private TweetsDAO tweetsDAO = TweetsDAOImp.getInstance();
	//private KeywordsAnalyzer keywordAnalyzer = new KeywordsAnalyzer();
	private ArrayList<String> trendsList;
	private ArrayList<String> newTrendsList = null;
	private Logger logger;
	
	/*public static TweetsCollector getInstance(){
		return uniqueInstance;
	}*/
	
	public void run() {
		super.run();
		while(true){
				Twitter twitter = new TwitterFactory().getInstance();
				String trend = "UCLA";
				Query query = new Query();
				query.setQuery(trend);
				query.setLang("en");
				Date date = new Date();
				String dateNow = "2"+ date.getYear() + "-" + (date.getMonth()+1) + "-" + date.getDate();
				query.setSince(dateNow);
				try {
					QueryResult qr = twitter.search(query);
					List<Tweet> tws = qr.getTweets();
					//ArrayList<Long> existingTweetList = tweetsDAO.getTweetsIDsByTrend(trend, date);
					//ArrayList<Tweet> filtedTweetList = filtTweetList(tws,existingTweetList);
					tweetsDAO.saveTweets(tws,trend,date);
					//keywordAnalyzer.analyze(filtedTweetList, trend, date);
				} catch (Exception e) {
					logger.error("", e);
				}	
			if(newTrendsList != null){
				trendsList = newTrendsList;
				newTrendsList = null;
			}
		}
	}
	
	public void output(){
		Date date = new Date();
		ArrayList<String> tweets = tweetsDAO.getTweetsText();
		FileUtil.outputFile("texts.txt", tweets);
	}
	
	public TweetsCollector(){
		PropertyConfigurator.configure("log4jcfg.txt");
		try {
			ConnectionPool.getInstance().createPool();
		} catch (Exception e) {
			logger.error("ConnectionPool failed to lauch.", e);
			System.exit(1);
		}
		logger = Logger.getLogger(TweetsCollector.class);
	}
	
	public void updateTrendsList(){
	}
	
	public static void main(String[] args) {
		new TweetsCollector().output();
	}
}
